package jus.aor.mobilagent.hostel;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import jus.aor.mobilagent.kernel._Service;

public class Annuaire  implements _Service<String> {

	private DocumentBuilder docBuilder ;
	private Document doc;
	private Map <String, Numero> hotelNumero ;
	
	public Annuaire(Object ... params) throws ParserConfigurationException {
		super();
		hotelNumero = new HashMap<String, Numero>();
		
		try {
			File f =new File((String)params[0]);
			
			/* Recuperation de l'annuaire dans le fichier xml */	
			docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			if (f.exists())
			{
				doc=docBuilder.parse(f) ;
			
				String name,numero="";
				NodeList list = doc.getElementsByTagName("Telephone");
				
	
				NamedNodeMap attrs;
				
				/* acquisition de toutes les entrees de l'annuaire */
				for(int i =0; i<list.getLength();i++) {
					attrs = list.item(i).getAttributes();
					name=attrs.getNamedItem("name").getNodeValue();
					numero=attrs.getNamedItem("numero").getNodeValue();
					hotelNumero.put(name,new Numero(numero));
				}			
			}
			else
				System.err.println(" le fichier n'exite pas! ");
	
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	@Override
	public String call(Object... params) throws IllegalArgumentException {
		
		for(Map.Entry<String, Numero> entry : hotelNumero.entrySet()) {
		    String cle = entry.getKey();
		    Numero valeur = entry.getValue();
		    if(cle.equals(params[0]))
		    	return valeur.numero;
		}
		return null;
	}

}
